//
//  ApproveReplyViewController.m
//  pushNewsManager
//
//  Created by Jobs on 8/3/17.
//  Copyright © 2017 com.Iori. All rights reserved.
//

#import "ApproveReplyViewController.h"
#import "Header.h"
#import "ApproveReplyTableViewCell.h"
#import "ReportEntity.h"
#import "CMTEntity.h"
#import "GetCMTApi.h"
#import "GetReportApi.h"
#import "DeleteCMTApi.h"
#import "DeleteReportApi.h"

@interface ApproveReplyViewController () <UIGestureRecognizerDelegate>

@property (nonatomic, strong) NSArray<CMTEntity*> *dataSource;
@property (nonatomic, strong) NSArray<ReportEntity*> *dataSourceReport;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger currentPageReport;
@property (nonatomic, assign) NSInteger totalCount;

@end

@implementation ApproveReplyViewController

#pragma mark - loadDataFromServer -
-(void)loadNewsDataFromServerWithCompleteBlock:(void (^)(BOOL finished))success
{
    WS(weakSelf);
    if(self.btnApprovesCollection[1].isSelected)
    {
        GetReportApi *api = [GetReportApi new];
        api.admin_id = [UserInfo sharedUser].admin.admin_id;
        api.page = 1;
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            if([IoriJsonHelper getErrorCode:request] == 100)
            {
                weakSelf.currentPageReport = 1;
                weakSelf.dataSourceReport = [NSArray yy_modelArrayWithClass:[ReportEntity class] json:[IoriJsonHelper getDictForKey:@"list" fromDict:request.responseJSONObject]];
                weakSelf.totalCount = [IoriJsonHelper getIntegerForKey:@"total" fromDict:request.responseJSONObject];
                [weakSelf.tableView reloadData];
                if(success)
                {
                    success(YES);
                }
            }
            else
            {
                if(success)
                {
                    success(NO);
                }
            }
        } failure:^(YTKBaseRequest *request) {
            if(success)
            {
                success(NO);
            }
        }];
    }
    else
    {
        GetCMTApi *api = [GetCMTApi new];
        api.page = 1;
        api.admin_id = [UserInfo sharedUser].admin.admin_id;
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            if([IoriJsonHelper getErrorCode:request] == 100)
            {
                weakSelf.currentPage = 1;
                weakSelf.dataSource = [NSArray yy_modelArrayWithClass:[CMTEntity class] json:[IoriJsonHelper getDictForKey:@"list" fromDict:request.responseJSONObject]];
                weakSelf.totalCount = [IoriJsonHelper getIntegerForKey:@"total" fromDict:request.responseJSONObject];
                [weakSelf.tableView reloadData];
                if(success)
                {
                    success(YES);
                }
            }
            else
            {
                if(success)
                {
                    success(NO);
                }
            }
        } failure:^(YTKBaseRequest *request) {
            if(success)
            {
                success(NO);
            }
        }];
    }
}

-(void)addNewsDataFromServerWithCompleteBlock:(void (^)(BOOL finished))success
{
    WS(weakSelf);
    
    if(self.btnApprovesCollection[1].isSelected)
    {
        GetReportApi *api = [GetReportApi new];
        api.page = self.currentPageReport +1;
        
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request)
         {
             if([IoriJsonHelper getErrorCode:request] == 100)
             {
                 if(success)
                 {
                     success(YES);
                 }
                 weakSelf.currentPageReport++;
                 NSArray<ReportEntity*> *__result = [NSArray yy_modelArrayWithClass:[ReportEntity class] json:[IoriJsonHelper getDictForKey:@"list" fromDict:request.responseJSONObject]];
                 if(__result.count < 1) return ;
                 if(weakSelf.dataSourceReport == nil)
                 {
                     weakSelf.dataSourceReport = __result;
                 }
                 else
                 {
                     NSMutableArray *arrayNew = [NSMutableArray arrayWithCapacity:10];
                     [arrayNew addObjectsFromArray:weakSelf.dataSourceReport];
                     [arrayNew addObjectsFromArray:__result];
                     weakSelf.dataSourceReport = arrayNew;
                 }
                 [weakSelf.tableView reloadData];
             }
             else
             {
                 if(success)
                 {
                     success(NO);
                 }
             }
         } failure:^(YTKBaseRequest *request) {
             if(success)
             {
                 success(NO);
             }
         }];
    }
    else
    {
        GetCMTApi *api = [GetCMTApi new];
        api.page = self.currentPage +1;
        
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request)
         {
             if([IoriJsonHelper getErrorCode:request] == 100)
             {
                 if(success)
                 {
                     success(YES);
                 }
                 weakSelf.currentPage++;
                 NSArray<CMTEntity*> *__result = [NSArray yy_modelArrayWithClass:[CMTEntity class] json:[IoriJsonHelper getDictForKey:@"list" fromDict:request.responseJSONObject]];
                 if(__result.count < 1) return ;
                 if(weakSelf.dataSource == nil)
                 {
                     weakSelf.dataSource = __result;
                 }
                 else
                 {
                     NSMutableArray *arrayNew = [NSMutableArray arrayWithCapacity:10];
                     [arrayNew addObjectsFromArray:weakSelf.dataSource];
                     [arrayNew addObjectsFromArray:__result];
                     weakSelf.dataSource = arrayNew;
                 }
                 [weakSelf.tableView reloadData];
             }
             else
             {
                 if(success)
                 {
                     success(NO);
                 }
             }
         } failure:^(YTKBaseRequest *request) {
             if(success)
             {
                 success(NO);
             }
         }];
    }
}

#pragma mark - view cycle -

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    id target = self.navigationController.interactivePopGestureRecognizer.delegate;
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:target action:@selector(handleNavigationTransition:)];
    pan.delegate = self;
    [self.view addGestureRecognizer:pan];
    self.tableView.estimatedRowHeight = 44; // some constant value
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    WS(weakself);
    [self.tableView addPullToRefreshWithActionHandler:^{
        [weakself loadNewsDataFromServerWithCompleteBlock:^(BOOL finished){
            [weakself.tableView.pullToRefreshView stopAnimating];
        }];
    }];
    self.tableView.av_footer = [AVFooterRefresh createFooterWithRefreshingBlock:^{
        [weakself addNewsDataFromServerWithCompleteBlock:^(BOOL finished) {
            [weakself.tableView.av_footer endFooterRefreshing];
        }];
    } scrollView:self.tableView];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakself.tableView triggerPullToRefresh];
    });
    
    self.tableView.av_footer.activityFooter.color = [UIColor whiteColor];
    self.tableView.av_footer.footerLabel.textColor = [UIColor whiteColor];
    self.tableView.av_footer.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    
    self.tableView.pullToRefreshView.textColor = [UIColor whiteColor];
    self.tableView.pullToRefreshView.arrowColor = [UIColor whiteColor];
    self.tableView.pullToRefreshView.activityIndicatorViewColor = [UIColor whiteColor];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    CGPoint point = [(UIPanGestureRecognizer*)gestureRecognizer translationInView:self.view];
    if(point.x<0)
    {
        return false;
    }
    return YES;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

#pragma mark -table delegate-

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(self.btnApprovesCollection[1].isSelected)
    {
        return self.dataSourceReport.count;
    }
    return self.dataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0)
        return 30;
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(section != 0) return nil;
    UILabel *labTitle = [[UILabel alloc] init];
    labTitle.text = [@"    " stringByAppendingString:[NSString stringWithFormat:@"%li条新增评论", (long)self.totalCount]];
    labTitle.textColor = [UIColor whiteColor];
    if(self.btnApprovesCollection[1].isSelected)
    {
        labTitle.text = [@"    " stringByAppendingString:[NSString stringWithFormat:@"%li条新增举报", (long)self.totalCount]];
    }
    return labTitle;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 20;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UILabel *lab = [[UILabel alloc] init];
    lab.textColor = [UIColor whiteColor];
    NSString *strTime = nil;
    if(self.btnApprovesCollection[1].isSelected)
    {
        strTime = self.dataSourceReport[section].report_ctime;
    }
    else
    {
        strTime = self.dataSource[section].cmt_ctime;
    }
    if(strTime.length > 0)
    {
        lab.text = [@"    " stringByAppendingString:strTime];
    }
    else
    {
        lab.text = @"";
    }
    lab.font = [UIFont systemFontOfSize:13];
    return lab;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    if(self.btnApprovesCollection[1].isSelected)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        ApproveReplyTableViewCell *__cell = (ApproveReplyTableViewCell*)cell;
        __cell.parentTable = tableView;
        __cell.parentVC = self;
        __cell.labName.text = self.dataSourceReport[indexPath.section].member_nickname;
        [__cell.imageHead sd_setImageWithURL:[NSURL URLWithString:self.dataSourceReport[indexPath.section].member_pic] placeholderImage:[UIImage imageNamed:@"nan1"]];
        __cell.labComment.text = self.dataSourceReport[indexPath.section].report_content;
        
        __cell.labTitle.text = self.dataSourceReport[indexPath.section].other_title;
        __cell.imageHead.layer.cornerRadius = 10;
    }
    else
    {
        cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        ApproveReplyTableViewCell *__cell = (ApproveReplyTableViewCell*)cell;
        __cell.parentTable = tableView;
        __cell.parentVC = self;
        __cell.labName.text = self.dataSource[indexPath.section].member.member_nickname;
        [__cell.imageHead sd_setImageWithURL:[NSURL URLWithString:self.dataSource[indexPath.section].member.member_pic] placeholderImage:[UIImage imageNamed:@"nan1"]];
        __cell.labComment.text = self.dataSource[indexPath.section].cmt_content;
        __cell.imageHead.layer.cornerRadius = 10;
    }
    
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  UITableViewAutomaticDimension;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WS(weakSelf);
    if(self.btnApprovesCollection[1].isSelected)
    {
        UITableViewRowAction *action_delete = [UITableViewRowAction
                                               rowActionWithStyle: UITableViewRowActionStyleDefault
                                               title: @"  删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath)
                                               {
                                                   [tableView setEditing:NO animated:YES];
                                                   DeleteReportApi *api = [DeleteReportApi new];
                                                   api.admin_id = [UserInfo sharedUser].admin.admin_id;
                                                   api.report_id = weakSelf.dataSourceReport[indexPath.section].report_id;
                                                   [MessageBox displayLoadingInView:weakSelf.view];
                                                   [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                                                       [MessageBox removeLoading];
                                                       if([IoriJsonHelper getErrorCode:request] == 100)
                                                       {
                                                           NSMutableArray *tempDataSource = [NSMutableArray arrayWithArray:weakSelf.dataSourceReport];
                                                           [tempDataSource removeObjectAtIndex:indexPath.section];
                                                           weakSelf.dataSourceReport = tempDataSource;
                                                           [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
                                                       }
                                                       else
                                                       {
                                                           [weakSelf showMessage:[IoriJsonHelper getError:request]];
                                                       }
                                                   } failure:^(YTKBaseRequest *request) {
                                                       [weakSelf showMessage:request.description];
                                                       [MessageBox removeLoading];
                                                   }];

                                               }];
        return @[action_delete];
    }
    else
    {
        UITableViewRowAction *action_delete = [UITableViewRowAction
                                               rowActionWithStyle: UITableViewRowActionStyleDefault
                                               title: @"  删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath)
                                               {
                                                   [tableView setEditing:NO animated:YES];
                                                   DeleteCMTApi *api = [DeleteCMTApi new];
                                                   api.admin_id = [UserInfo sharedUser].admin.admin_id;
                                                   api.cmt_id = weakSelf.dataSource[indexPath.section].cmt_id;
                                                   [MessageBox displayLoadingInView:weakSelf.view];
                                                   [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                                                       [MessageBox removeLoading];
                                                       if([IoriJsonHelper getErrorCode:request] == 100)
                                                       {
                                                           NSMutableArray *tempDataSource = [NSMutableArray arrayWithArray:weakSelf.dataSource];
                                                           [tempDataSource removeObjectAtIndex:indexPath.section];
                                                           weakSelf.dataSource = tempDataSource;
                                                           [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
                                                       }
                                                       else
                                                       {
                                                           [weakSelf showMessage:[IoriJsonHelper getError:request]];
                                                       }
                                                   } failure:^(YTKBaseRequest *request) {
                                                       [weakSelf showMessage:request.description];
                                                       [MessageBox removeLoading];
                                                   }];
                                               }];
        UITableViewRowAction *action_state = [UITableViewRowAction
                                              rowActionWithStyle: UITableViewRowActionStyleNormal
                                              title: @" 清理" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath)
                                              {
                                                  [tableView setEditing:NO animated:YES];
                                                  SetCMTClearApi *api = [SetCMTClearApi new];
                                                  api.admin_id = [UserInfo sharedUser].admin.admin_id;
                                                  api.member_id = weakSelf.dataSource[indexPath.section].member_id;
                                                  [MessageBox displayLoadingInView:weakSelf.view];
                                                  [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                                                      [MessageBox removeLoading];
                                                      if([IoriJsonHelper getErrorCode:request] == 100)
                                                      {
                                                          [weakSelf.tableView triggerPullToRefresh];
                                                          [weakSelf showMessage:@"清理成功"];
                                                      }
                                                      else
                                                      {
                                                          [weakSelf showMessage:[IoriJsonHelper getError:request]];
                                                      }
                                                  } failure:^(YTKBaseRequest *request) {
                                                      [weakSelf showMessage:request.description];
                                                      [MessageBox removeLoading];
                                                  }];
                                              }];
        return @[action_delete , action_state];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
}

#pragma mark -action-
- (IBAction)btnApprove_click:(UIButton *)sender
{
    [self.tableView setEditing:NO animated:YES];
    if(sender == self.btnReport)
    {
        self.btnSearch.hidden = YES;
    }
    else
    {
        self.btnSearch.hidden = NO;
    }
    [self.btnApprovesCollection enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIControl *control = (UIControl*)obj;
        [control setSelected:NO];
    }];
    [sender setSelected:YES];
    [self.tableView triggerPullToRefresh];
}

- (IBAction)btnApproveNews_click:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


@end
